<template>
	 <div style="width: 100%; height: 100%" :style="{ 'background': config.config.property.bgColor }">
	     <div id="main" ref="chartContainer" style="width: 100%; height: 100%"></div>
	   </div>
</template>
<script>
	import * as echarts from 'echarts'
	import chartBase from '@/mixin/chart-base.js';
	import emitComponentBase from '@/mixin/emit-component-base.js';
	import dataModel from '@/models/panel-config-data.js';
	import {
		checkNegative
	} from '@/utils/util';
	import {
		mapState
	} from 'vuex';
	import config from './config/config';
	export default {
		name: 'StartStopCurve',
		components: {

		},
		mixins: [chartBase, emitComponentBase],
		props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h', 'Item'],
		data() {
			return {
				chart: null, // 存储echarts实例
				      echartsOptionData: [
				        {
				          'val': '0',
				          'time': '00:00',
				        },
				        {
				          'val': '1',
				          'time': '04:00',
				        },
				        {
				          'val': '1',
				          'time': '08:00',
				        },
				        {
				          'val': '0',
				          'time': '12:00',
				        },
				        {
				          'val': '0',
				          'time': '16:00',
				        },
				        {
				          'val': '1',
				          'time': '20:00',
				        },
				        {
				          'val': '1',
				          'time': '24:00',
				        },
				      ],
			};
		},
		computed: {
			...mapState({}),
		},
		watch: {

		},
		created() {
			this.orgConfig = config;
			this.config = JSON.parse(JSON.stringify(this.orgConfig));
			this.chartId = `${this.widgetInstanceId}_01`;

		},
		mounted() {
			if (window.isLocalEnv) {
				this.loadWidget();
			}
		},
		methods: {

			// 初始加载时 以及 编排面更改配置时 触发
			loadWidget(pageStatus) {
				this.pageStatus = pageStatus;
				this.updateConfigProperty();
				this.updateConfigData();
				if (window.isLocalEnv || this.emitComponentStatus) {
					this.updateParams(pageStatus);
					if (!this.isRealTime) {
						this.debounceGetData();
					}
				}
				this.afterLoadWidget();
				this.checkNegative(this.apiResult);
			},

			// 接收xvue发来的实时数据
			handleRealTimeCommunication(realTimeData) {
				if (this.config.config.property.isDebounce && this.isStopRealData) {
					return;
				}

				const result = this.getResult(realTimeData);
				if (this.isNoData || this.autoRefreshIsSameRes(result)) {
					this.isLoading = false;
					return;
				}
				const {
					data,
					property
				} = this.config.config;

				// api请求，拿到数据
				if (data.dataSourceType !== 'xMinerRedisRealTime') {
					this.getCorrectParams(this.params, data.dataSourceType); // 参数存入xvue，导出数据时使用
				}
				// this.apiResult = result;
				// this.lastParams = null;
				// this.sendDataToConfig(result);
				// const convertedData = convertData(result, property);
				// if (convertedData === -1) {
				//   this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
				//   this.setDataException();
				//   return;
				// }
				// this.generateChart(convertedData);
				// this.isLoading = false;
			},
			acceptEvtMsg(paramters, key, obj) {
				this.checkUpdateParams(obj);
			},
			checkUpdateParams(obj) {
				// 检查下是否和本组件有关
				const _obj = obj || {};
				let oo = {}
				let flag = false;
				for (const key in _obj) {
					if (key.indexOf(EMIT_PARAMS_OBJ) > -1) {
						const o = _obj[key];
						if (o.eventKey) {
							const event = this.config.events.find(e => e.type === 'in' && e.key === o.eventKey);
							if (event) {
								flag = true;
								oo = o
							}
							break;
						}
					}
				}
				if (flag) {
					// 和本组件有关再执行组件接收到事件后的相关操作
					console.log('_obj', _obj)
					console.log('oo', oo)

					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const alarm_id = oo?.parameters[oo?.keys[0]]
					let param = {
						code: 'alarm_id',
						value: alarm_id
					}
					let paramOo = [param]

					// api请求，拿到数据
					const {
						data
					} = this.config.config
					this.isLoading = true
					const method = `getChartData${data.dataSourceType}`;
					const trueParams = this.getCorrectParams(this.params, data.dataSourceType);
					trueParams = {
						...trueParams,
						params: paramOo,
					};

					dataModel[method](trueParams, data)
						.then(result => {
							this.echartsOptionData.length = 0
							          this.echartsOptionData = result.data
							          this.echartsOptionfunction(this.echartsOptionData)
						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				}
			},
			getChartData() {
				const {
					data,
					property
				} = this.config.config;

				// 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
				if (data.dataSourceType === 'staticData') {
					this.echartsOptionfunction(this.echartsOptionData)
					// 重置数据异常状态
					this.resetAbnormalType();
					return;
				}

				// api请求，拿到数据
				if (data.dataSourceType) {
					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const method = `getChartData${data.dataSourceType}`;
					const params = this.getCorrectParams(this.params, data.dataSourceType);
					dataModel[method](params, data)
						.then(result => {
							this.echartsOptionData.length = 0
							          this.echartsOptionData = result.data
							          this.echartsOptionfunction(this.echartsOptionData)
							// 重置数据异常状态
							this.resetAbnormalType();
							this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
							if (this.autoRefreshIsSameRes(result)) {
								return;
							}

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				} else {
					// 如果在用户面，则给提示
					if (this.$route.name === 'userHomePage') {
						this.$message({
							message: this.$demoi18n('view.dataSourceTypeEmpty'),
							type: 'warning',
						});
					}
				}
			},
			
			    echartsOptionfunction(echartsData) {
			      console.log('图表内', echartsData)
			      const dateArr = []
			      const yArr1 = []
			      const yArr2 = []
			      echartsData.forEach((item) => {
			        dateArr.push(item.time)
			        if (item.val == 1) {
			          yArr1.push(item.val)
			          yArr2.push(null)
			        } else {
			          yArr1.push(null)
			          yArr2.push(item.val)
			        }
			      })
			      const option = {
			        grid: {
			          top: `${this.config.config.property.top}%`,
			          left: `${this.config.config.property.left}%`, // 距离容器左侧的距离
			          right: `${this.config.config.property.right}%`, // 距离容器右侧的距离
			          bottom: `${this.config.config.property.bottom}%`, // 距离容器底部的距离
			          containLabel: true, // grid区域是否包含坐标轴的标签
			        },
			        title: {
			          text: '',
			        },
			        tooltip: {
			          trigger: 'axis',
			        },
			        xAxis: {
			          type: 'category',
			          data: dateArr,
			          boundaryGap: false,
			          axisLabel: {
			            color: this.config.config.property.xlincolor,
			            fontSize: this.config.config.property.xlinSize,
			          },
			          axisLine: {
			            lineStyle: {
			              color: '#f0f8ff', // 设置 X 轴线的颜色
			            },
			          },
			        },
			        yAxis: {
			          type: 'value',
			          min: 0,
			          max: 1,
			          interval: 1,
			          axisLabel: {
			            formatter: function (value) {
			              return value === 1 ? '开1' : '关0'
			            },
			            color: this.config.config.property.ylincolor,
			            fontSize: this.config.config.property.ylinSize,
			          },
			        },
			        series: [
			          {
			            name: '开1',
			            type: 'line',
			            data: yArr1, // 开的状态
			            step: 'start',
			            symbol: 'none',
			            itemStyle: {
			              color: this.config.config.property.runColor, // 开1的颜色
			            },
			            lineStyle: {
			              width: this.config.config.property.lineWidth,
			            },
			          },
			          {
			            name: '关0',
			            type: 'line',
			            data: yArr2, // 关的状态
			            step: 'start',
			            symbol: 'none',
			            itemStyle: {
			              color: this.config.config.property.stopColor, // 关0的颜色
			            },
			            lineStyle: {
			              width: this.config.config.property.lineWidth,
			            },
			          },
			        ],
			      }
			      console.log(this.$refs?.chartContainer,9999);
			      
			      this.chart = echarts.init(this.$refs?.chartContainer)
			      this.chart.setOption(option)
			    },
			// itemClick(params) {
			// 	console.log(this.widgetInstanceId)
			//   const orgEvtKey = this.orgConfig.events[0].key
			//   const outEvt = this.config.events[0]
			//   const { key } = outEvt.parameters[0] // key: 对应xminer接口中的参数/编码
			//   const { paramKey } = outEvt // paramKey: 对应数据面板中的字段名，如s，y
			//   console.log('=======params============', params)
			//   const outObj = {
			//     emit_params_obj: {
			//       eventKey: outEvt.key,
			//       type: 'terms',
			//       keys: [key],
			//       parameters: {
			//         [key]: params[paramKey],
			//       },
			//       widgetInstanceId: this.widgetInstanceId,
			//       sendTime: new Date().getTime(),
			//     },
			//   }
			//   // console.log("===================",outObj)
			//   // xvue提供的emit方法，用于发出事件的
			//   if (import.meta.env.PROD) {
			//     adapterComponent.emit(orgEvtKey, outObj)
			//   } else {
			//     emit(orgEvtKey, outObj)
			//   }
			// },
			// getTooltip() {
			//   return {
			//     config: this.config.config.property.tooltip || {},
			//     vars: {},
			//     params: this.params,
			//     parentComp: this,
			//   };
			// },
			checkNegative,
			// itemClick(params, data) {
			// 	console.log(params)
			//   this.chartClick(params, data);
			//   if (params) {
			//     this.sendAdvancedLinkagge({...params});
			//   }
			// },
			// handleAsTooltip(filterRes) {
			//   const { property } = this.config.config;
			//   const convertedData = convertData(filterRes, property);
			//   this.generateChart(convertedData);
			// },
		},
	};
</script>
<style lang="less" scoped>
	// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
	@import '../../common/chart.less';
</style>
<style>
	/* 全局loading样式修改 */

	.chartMain .loading .el-loading-spinner .circular {
		width: 34px !important;
		height: 34px !important;
	}

	.chartMain .el-dialog__header {
		padding: 9px 20px 10px !important;
		background: #2a3352 !important;
		text-align: left;
		box-sizing: border-box;
		height: 50px;
		line-height: 32px;
	}

	.chartMain .el-dialog__title {
		text-align: left;
		/* font-size: 18px; */
		line-height: 18px !important;
		color: #b2d3fe !important;
	}

	.chartMain .el-dialog__body {
		padding: 10px 20px 30px 20px;
		background: #1a2032 !important;
		line-height: 24px;
		font-size: 14px;
	}

	.chartMain .el-dialog__headerbtn .el-dialog__close {
		color: #b2d3fe !important;
	}

	.chartMain .dialog-footer {
		text-align: right;
		margin-bottom: -14px;
		margin-right: 4px;
	}

	.chartMain .el-dialog__headerbtn {
		top: 15px;
		/* font-size: 18px; */
	}
</style>
<style scoped lang="less">
  /deep/.el-progress-bar__outer {
    border-radius: 0 !important;
    background: none !important;
  }

  /deep/.el-progress-bar__inner {
    border-radius: 0 !important;
  }

  /deep/.el-progress__text {
    color: #ffffff;
  }

  .list_child {
    color: #ffffff;
    background-image: url(./image/sz.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    display: inline-flex;
    justify-content: center;
  }

  .gradient-progress {
    background-image: linear-gradient(to right, #ffc107, #e91e63);
  }
  .listChildchild{
    white-space: nowrap; /* 确保文本在一行内显示 */
              overflow: hidden; /* 超出部分隐藏 */
              text-overflow: ellipsis; /* 超出部分显示省略号 */
              cursor: pointer; /* 将鼠标指针变为手指形状 */
  }
</style>